package com.glo.quiki.req;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import org.jetbrains.annotations.NotNull;

import java.util.*;

/**
 * 自定义 CookieJar 让 OkHttp 自动存储和管理 Cookies
 */
public class QuikiSimpleCookieJar implements CookieJar {

	private final Map<String, List<Cookie>> cookieStore = new HashMap<>();
	private final Map<String, String> rememberTokens = new HashMap<>(); // 账号 -> remember_web_xxxx 令牌

	private static final String remember = "remember";

	@Override
	public void saveFromResponse(@NotNull HttpUrl url, @NotNull List<Cookie> cookies) {
		cookieStore.put(url.host(), new ArrayList<>(cookies));
		System.out.println("Saved cookies for " + url.host() + ": " + cookies);

		// 解析 remember_web_xxxx Cookiew
		for (Cookie cookie : cookies) {
			if (cookie.name().startsWith("remember_web_")) {
				rememberTokens.put(remember, cookie.name() + "=" + cookie.value());
			}
		}
	}

	@NotNull
	@Override
	public List<Cookie> loadForRequest(@NotNull HttpUrl url) {
		return new ArrayList<>(cookieStore.getOrDefault(url.host(), new ArrayList<>()));
	}

	/**
	 * 获取指定主机的所有 Cookie
	 *
	 * @param host 目标站点
	 * @return 纯净的 Cookie 键值对列表
	 */
	public List<String> getCookies(String host) {
		List<String> result = new ArrayList<>();
		List<Cookie> cookies = cookieStore.getOrDefault(host, Collections.emptyList());

		for (Cookie cookie : cookies) {
			result.add(cookie.name() + "=" + cookie.value());
		}

		return result;
	}

	/**
	 * 获取指定 Cookie 名称的值
	 *
	 * @param host       目标站点
	 * @param cookieName 需要获取的 Cookie 名称
	 * @return Cookie 值，如果不存在返回 null
	 */
	public String getCookieValue(String host, String cookieName) {
		List<Cookie> cookies = cookieStore.getOrDefault(host, Collections.emptyList());
		for (Cookie cookie : cookies) {
			if (cookie.name().equals(cookieName)) {
				return cookie.value();
			}
		}
		return null;
	}

	/**
	 * 获取指定账号的 remember_web_xxx 令牌
	 *
	 * @return remember_web_xxx 令牌值，如果不存在返回 null
	 */
	public String getRememberToken() {
		return rememberTokens.get(remember);
	}

}
